<template>
  <div class="server-manage-container">
    <div class="server-header">
      <el-button @click='popup("add")' type="primary" class="add-server-btn">
        <el-icon><Plus /></el-icon>添加机器
      </el-button>
      <div class="server-stats">
        <el-tag type="info">总机器数: {{ serverList.length }}</el-tag>
        <el-tag type="success">在线: {{ getActiveServersCount }}</el-tag>
      </div>
    </div>
    
    <el-scrollbar height="calc(100vh - 150px)">
      <div class="server-list-container">
        <el-card v-for="(server, index) in serverList" :key="server.id" class="server-card" 
                :shadow="server.default_code ? 'always' : 'hover'"
                :class="{'default-server': server.default_code}">
          <template #header>
            <div class="server-card-header">
              <div class="server-name">
                <el-tag size="small" type="info" class="server-index">{{ index + 1 }}</el-tag>
                <span class="name-text">{{ server.name }}</span>
                <el-tag v-if="server.default_code" size="small" type="success">默认</el-tag>
              </div>
              <div class="server-actions">
                <el-switch
                  @change='switchStatus(server)'
                  v-model="server.default_code"
                  active-color="#66b1ff" 
                  inactive-color="#b1b1b1"
                  active-text="默认"
                  inactive-text="非默认">
                </el-switch>
              </div>
            </div>
          </template>
          
          <div class="server-info">
            <div class="server-details">
              <div class="detail-item">
                <el-icon><Location /></el-icon>
                <span>{{ server.host_ip }}:{{ server.host_port }}</span>
              </div>
              <div class="detail-item">
                <el-icon><User /></el-icon>
                <span>{{ server.creator }}</span>
              </div>
              <div class="detail-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ $tools.rTime(server.create_time) }}</span>
              </div>
            </div>
            
            <div class="server-status" :class="{'server-active': server.server_status === 'active'}">
              <el-tag :type="server.server_status === 'active' ? 'success' : 'info'" size="small">
                {{ server.server_status === 'active' ? '在线' : '未知' }}
              </el-tag>
            </div>
          </div>
          
          <div class="server-operations">
            <el-button @click="testConnection(server)" type="warning" size="small" :loading="server.testing">
              <el-icon><Connection /></el-icon>测试连接
            </el-button>
            <el-button @click="terminal(server.id)" type="success" size="small">
              <el-icon><View /></el-icon>进入终端
            </el-button>
            <el-button @click='popup("edit",server)' type="primary" size="small">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button @click="delServer(server.id)" type="danger" size="small">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </div>
        </el-card>
        
        <!-- 空状态显示 -->
        <el-empty v-if="serverList.length === 0" description="暂无服务器数据">
          <el-button @click='popup("add")' type="primary">添加第一台服务器</el-button>
        </el-empty>
      </div>
      
      <div class="pagination-container">
        <el-pagination  background layout="total, prev, pager, next, jumper"
                      @current-change="currentPages"
                      :default-page-size="100"
                      :total="pages.count"
                      :current-page="pages.current"
                      next-text="下一页" prev-text="上一页">
        </el-pagination>
      </div>
    </el-scrollbar>
    
    <!--  弹窗-->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" :before-close="closeDialog" top="40px" destroy-on-close custom-class="class_dialog" width="500px">
      <div class="system-icon-content">
        <el-form :model="serverData" :rules="rulesServer" ref="ServerRef" label-position="top">
          <el-form-item label="名称" prop="name">
            <el-input v-model="serverData.name" placeholder="请输入名称">
              <template #prefix><el-icon><Monitor /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item label="服务器IP" prop="host_ip">
            <el-input v-model="serverData.host_ip" maxlength="15" placeholder="请输入服务器IP">
              <template #prefix><el-icon><Location /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item label="端口号" prop="host_port">
            <el-input v-model="serverData.host_port" maxlength="15" placeholder="请输入端口号">
              <template #prefix><el-icon><Position /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="sys_user_name">
            <el-input v-model="serverData.sys_user_name" maxlength="200" placeholder="请输入用户名">
              <template #prefix><el-icon><User /></el-icon></template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="sys_user_passwd">
            <el-input v-model="serverData.sys_user_passwd" maxlength="200" placeholder="请输入密码" show-password>
              <template #prefix><el-icon><Lock /></el-icon></template>
            </el-input>
          </el-form-item>
          
          <el-form-item v-if="dialogType === 'add'">
            <el-checkbox v-model="serverData.default_code" label="设为默认服务器" border />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button v-if="dialogTitle === '添加机器'" type="primary" @click="clickAdd">保 存</el-button>
          <el-button v-if="dialogTitle === '编辑机器'" type="primary" @click="clickUpdate">保 存</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapMutations, mapState} from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, View, Connection, Location, User, Calendar, Edit, Delete, Monitor, Position, Lock } from '@element-plus/icons-vue';

export default {
  components: {
    Plus,
    View,
    Connection,
    Location,
    User,
    Calendar,
    Edit,
    Delete,
    Monitor,
    Position,
    Lock
  },
  computed: {
    ...mapState({
      server: state => state.server,
      pro: state => state.pro
    }),
    username() {
			return window.sessionStorage.getItem('username');
		},
    getActiveServersCount() {
      return this.serverList.filter(server => server.server_status === 'active').length;
    }
  },
  data() {
    return {
        dialogVisible:false,
        dialogType: '', // 对话框类型，用于区分不同类型的对话框
        dialogTitle: '', // 对话框标题，根据不同类型动态设置
        serverList: [],
        serverData: {
          name: '',
          host_ip: '',
          host_port: '',
          sys_user_name: '',
          sys_user_passwd: '',
          creator: '',
          project: '',
          default_code: false
        },
        pages: {
          count: 0,
          current: 1
        },
        rulesServer: {
          name: [
            { required: true, message: '请输入机器名称', trigger: 'blur' },
          ],
          host_ip: [
            { required: true, message: '请输入服务器IP', trigger: 'blur' },
          ],
          host_port: [
            { required: true, message: '请输入端口号', trigger: 'blur' },
          ],
          sys_user_name: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ],
          sys_user_passwd: [
            { required: true, message: '请输入密码', trigger: 'blur' },
          ],
        },
    }
  },
  methods: {
    ...mapMutations(['servers']),

    async testConnection(server) {
      // 防止重复测试
      if (server.testing) return;

      // 设置测试状态
      server.testing = true;

      try {
        const params = {
          host_ip: server.host_ip,
          host_port: server.host_port,
          sys_user_name: server.sys_user_name,
          sys_user_passwd: server.sys_user_passwd
        };

        const response = await this.$api.testServerConnections(params, server.id);
        
        if (response.status === 200) {
          const result = response.data;
          
          if (result.success) {
            this.$message({
              type: 'success',
              message: result.message || '连接测试成功',
              duration: 3000
            });
            
            // 更新服务器状态
            server.server_status = 'active';
            
          } else {
            this.$message({
              type: 'error',
              message: result.message || '连接测试失败',
              duration: 5000
            });
            
            // 更新服务器状态
            server.server_status = 'error';
          }
        }
      } catch (error) {
        console.error('连接测试错误:', error);
        
        // 更新服务器状态
        server.server_status = 'error';
        
        // 显示简单的错误提示
        let errorMessage = '连接测试失败';
        
        if (error.response && error.response.data) {
          const errorData = error.response.data;
          errorMessage = errorData.message || '连接测试失败';
        } else if (error.message) {
          errorMessage = `连接测试失败：${error.message}`;
        }
        
        this.$message({
          type: 'error',
          message: errorMessage,
          duration: 5000
        });
        
      } finally {
        // 取消测试状态
        server.testing = false;
      }
    },



    terminal(id){
      this.$router.push({name: 'terminal'});
      this.servers(id)
    },

    currentPages(currentPage) {
      this.getServerList(this.pro.id,currentPage)
      this.pages.current = currentPage
    },

    async getServerList() {
     const response =await this.$api.getServers(this.pro.id,1)
     if (response.status ===200){
        // 确保每个服务器对象都有testing属性
        this.serverList = response.data.result.map(server => ({
          ...server,
          testing: false,
          server_status: server.server_status || 'unknown'
        }));
        this.pages = response.data
			}
    },

    async switchStatus(data) {
    let params = {default_code:data.default_code}
    const response =await this.$api.updateServer(data.id,params)
    if (response.status ===200){
				ElMessage({
					type: 'success',
					message: '设置成功'
				});
			}
    this.getServerList()
    },

    delServer(id) {
    ElMessageBox.confirm('此操作将永久删除该机器, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const response = await this.$api.delServer(id)
        if(response.status ===204){
          ElMessage({
            type: 'success',
            message: '删除成功!'
          });
          // 刷新页面
          this.getServerList(this.pro.id,1);
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    async clickUpdate() {
      this.$refs.ServerRef.validate(async vaild => {
      // 判断是否验证通过，不通过则直接retrue
      if (!vaild) return;
      const params = {...this.serverData}
      const response = await this.$api.updateServer(this.serverData.id,params);
      if (response.status === 200) {
        ElMessage({
          type: 'success',
          message: '修改成功',
          duration: 1000
       });
       this.dialogVisible= false;
       // 清除表单验证状态
       this.$refs.ServerRef.clearValidate();
       this.getServerList(this.pro.id,1);
      }
      })
    },

    async clickAdd() {
      this.$refs.ServerRef.validate(async vaild => {
      // 判断是否验证通过，不通过则直接retrue
      if (!vaild) return;
      const params = {...this.serverData}
      const response = await this.$api.createServer(params);
      if (response.status === 201) {
        ElMessage({
          type: 'success',
          message: '添加成功',
          duration: 1000
        });
        this.dialogVisible= false;
        // 清除表单验证状态
        this.$refs.ServerRef.clearValidate();
        this.getServerList(this.pro.id,1);
      }
      })
    },

    popup(type,data) {
      this.dialogType = type;
      this.dialogVisible = true;

      // 根据不同的对话框类型设置标题
      switch (type) {
        case 'add':
          this.dialogTitle = '添加机器';
          this.serverData = {
            name: '',
            host_ip: '',
            host_port: '',
            sys_user_name: '',
            sys_user_passwd: '',
            creator: this.username,
            project: this.pro.id,
            default_code: false
          };
          break;

        case 'edit':
          this.dialogTitle = '编辑机器';
          this.serverData = {...data};
          break;

        default:
          this.dialogTitle = '';
          break;
      }
    },

    closeDialog() {
      this.dialogVisible = false;
      this.getServerList(this.pro.id,1);
      // 重置表单数据为初始结构
      this.serverData = {
        name: '',
        host_ip: '',
        host_port: '',
        sys_user_name: '',
        sys_user_passwd: '',
        creator: '',
        project: '',
        default_code: false
      };
      // 清除表单验证状态
      if (this.$refs.ServerRef) {
        this.$refs.ServerRef.clearValidate();
      }
    },
  },

  created() {
    this.getServerList()
  }
}
</script>

<style scoped>
.server-manage-container {
  padding: 0 15px;
}

.server-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.server-stats {
  display: flex;
  gap: 10px;
}

.server-list-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
  padding-top: 5px; /* 添加顶部内边距，防止卡片悬浮时被裁剪 */
}

.server-card {
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e4e7ed; /* 添加默认边框颜色 */
}

.server-card:hover {
  transform: translateY(-3px); /* 减小上移距离，避免显示不全 */
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
  border-color: #c6e2ff; /* 悬浮时边框颜色变化 */
}

.default-server {
  border: 1px solid #67c23a;
  box-shadow: 0 0 8px rgba(103, 194, 58, 0.2); /* 为默认服务器添加轻微阴影 */
}

.server-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.server-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}

.name-text {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.server-info {
  display: flex;
  justify-content: space-between;
  margin: 15px 0;
}

.server-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.server-operations {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}


</style>